document.addEventListener('DOMContentLoaded', function () {
    const tableBody = document.getElementById('group-table-body');
    const refreshStatusEl = document.getElementById('refresh-status');

    // 获取i18n文本的辅助函数
    const getI18nText = (key, fallback) => {
        const element = document.querySelector(`[data-i18n="${key}"]`);
        return element ? element.textContent : fallback;
    };

    const updateGroupTable = async () => {
        try {
            const response = await fetch('/api/consumer-groups');
            if (!response.ok) {
                throw new Error(`Network response was not ok: ${response.statusText}`);
            }
            const groups = await response.json();

            // 保存当前展开的分组ID
            const expandedGroupIds = [];
            document.querySelectorAll('.group-row').forEach(row => {
                const subRow = row.nextElementSibling;
                if (subRow && !subRow.classList.contains('d-none')) {
                    expandedGroupIds.push(row.dataset.groupId);
                }
            });

            // 清空现有表格内容
            tableBody.innerHTML = '';

            if (groups.length === 0) {
                const noGroupsText = getI18nText('groups.no.groups', 'No active consumer groups found.');
                const emptyRow = `<tr><td colspan="3" class="text-center">${noGroupsText}</td></tr>`;
                tableBody.insertAdjacentHTML('beforeend', emptyRow);
            } else {
                // 根据新数据重新构建表格行
                groups.forEach(group => {
                    // 创建主行
                    const mainRow = document.createElement('tr');
                    mainRow.className = 'group-row';
                    // 添加数据属性存储分组ID，用于状态恢复
                    mainRow.dataset.groupId = group.groupId || group.groupName;
                    mainRow.innerHTML = `
                        <td><button class="btn btn-sm p-0 toggle-subtable"><i class="bi bi-chevron-right"></i></button></td>
                        <td>${escapeHtml(group.groupName)}</td>
                        <td>${group.totalLag}</td>
                    `;
                    tableBody.appendChild(mainRow);

                    // 创建子行（默认隐藏）
                    const subRow = document.createElement('tr');
                    subRow.className = 'subtable-row d-none';
                    subRow.innerHTML = `
                        <td colspan="3" class="p-0">
                            <div class="border-top border-bottom p-3 bg-light">
                              ${renderPartitionTable(group.partitionLags)}
                            </div>
                        </td>
                    `;
                    tableBody.appendChild(subRow);

                    // 如果是之前展开的分组，恢复展开状态
                    if (expandedGroupIds.includes(mainRow.dataset.groupId)) {
                        subRow.classList.remove('d-none');
                        const icon = mainRow.querySelector('i');
                        icon.classList.remove('bi-chevron-right');
                        icon.classList.add('bi-chevron-down');
                    }
                });

                // 添加展开/折叠事件监听
                attachToggleEventListeners();
            }

            // 更新状态指示器为“成功”
            const liveUpdateText = getI18nText('dashboard.live.update', 'Live Update');
            refreshStatusEl.innerHTML = '<span class="spinner-grow spinner-grow-sm text-success" role="status" aria-hidden="true"></span> ' + liveUpdateText;
        } catch (error) {
            console.error('Failed to fetch consumer group data:', error);
            // 更新状态指示器为“失败”
            const updateFailedText = getI18nText('groups.update.failed', 'Update Failed');
            refreshStatusEl.innerHTML = '<span class="spinner-grow spinner-grow-sm text-danger" role="status" aria-hidden="true"></span> ' + updateFailedText;
        }
    };

    // 新增：渲染分区详情子表格
    const renderPartitionTable = (partitionLags) => {
        if (!partitionLags || partitionLags.length === 0) {
            return `<div class="text-center text-muted italic">${getI18nText('groups.no.partition.data', 'No partition data available')}</div>`;
        }

        const topicPartitionText = getI18nText('groups.topic.partition', 'Topic:Partition');
        const committedOffsetText = getI18nText('groups.committed.offset', 'Committed Offset');
        const highWatermarkText = getI18nText('groups.high.watermark', 'High Watermark');
        const partitionLagText = getI18nText('groups.partition.lag', 'Partition Lag');

        let tableHtml = `
            <div class="table-responsive">
                <table class="table table-sm table-borderless mb-0">
                    <thead>
                        <tr class="table-secondary">
                            <th>${topicPartitionText}</th>
                            <th>${committedOffsetText}</th>
                            <th>${highWatermarkText}</th>
                            <th>${partitionLagText}</th>
                        </tr>
                    </thead>
                    <tbody>
        `;

        partitionLags.forEach(lag => {
            tableHtml += `
                    <tr>
                        <td>${escapeHtml(lag.topicPartition)}</td>
                        <td>${lag.committedOffset}</td>
                        <td>${lag.highWatermark}</td>
                        <td class="${lag.lag > 1000 ? 'text-danger fw-bold' : ''}">${lag.lag}</td>
                    </tr>
        `;
        });

        tableHtml += `
                </tbody>
            </table>
        </div>
      `;
      return tableHtml;
    };

    // 新增：添加展开/折叠事件监听
    const attachToggleEventListeners = () => {
        document.querySelectorAll('.toggle-subtable').forEach(button => {
            button.addEventListener('click', function() {
                const icon = this.querySelector('i');
                const mainRow = this.closest('.group-row');
                const subRow = mainRow.nextElementSibling;

                // 切换子表格显示状态
                subRow.classList.toggle('d-none');
                // 切换图标方向
                icon.classList.toggle('bi-chevron-right');
                icon.classList.toggle('bi-chevron-down');
            });
        });
    };

    // 新增：HTML转义函数，防止XSS攻击
    const escapeHtml = (text) => {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    };

    // 每 5 秒刷新一次
    setInterval(updateGroupTable, 5000);
    // 添加初始数据加载调用
    updateGroupTable();
});